//index.js
// 用户，商家，菜单，订单，子订单，支付，搜索，评价
var util =require('../../utils/util.js')
var voiceorder=require('../../utils/voiceorder.js')
var foodcart=require('../../utils/foodcart.js');
var app = getApp()
Page({
  data: {
    pageType: 1,
    // index
    userInfo: {},

    orderOrBusiness: 'order',
    newsarr: [
      { id: 0, message: "本店新用户立减2元（在线支付专享）" },
      { id: 1, message: "本店用户每天立减2元（在线支付专享）" },
    ],
    shopinfo: wx.getStorageSync("shopinfo") == null ? {} : wx.getStorageSync("shopinfo"),
    autoplay: true,
    interval: 3000,
    duration: 500,
    vertical: true,
    circular: true,

    menu: wx.getStorageInfoSync("menus") == null ? []:wx.getStorageInfoSync("menus"),

 
    height: 0,
    orderType: 0,  //点菜类型
    restaurant: true,  //餐厅点菜

    block: false,  //选规格
    foodtype: 0,  //选规格种类
    bindId: 0,
    tasteName:'',
 
    foodarr: [],
    cartlist:[],

    // me
    img: '' ,
    imghost: app.globalData.imghost,


    searchKey:'',
    shopid:5,


    open: false,   //是否打开红包
    page: true,   //红包是否显示 

    toView:'hotview',

    //语音相关
    voiceblock:false,
    voicesucc:false,
    voicetext:'按住右边图标语音点餐',
    nvoicetext:'',
    voices:'',
    voiceparsetip:'语音正在解析中...',
    foodnickarr: [],
    
    isfirstload:false,
    isauth:true,

    buycar_num: 0,
    totalMoney: 0, 

    open: false,   //是否打开红包
    redpacket: false,   //红包是否显示  
    redact:[],

    //收藏
    cslist:[],
    is_collect:false

  }, 
  onLoad: function (options) {
    var id=options.id;
    if (!id) id=5;
    this.setData({ shopid:id})
    if (id != wx.getStorageSync("shopid")){
      wx.removeStorageSync("foodlist");
    }
    wx.setStorageSync("shopid", id);
    var that = this  
    that.foodlist();
    that.getShopInfo(); 
    if (!wx.getStorageSync("userinfo") || wx.getStorageSync("userinfo")===''){
      wx.navigateTo({
        url: '/pages/userauth/userauth',
      })
      return;
    }
    let userInfo = JSON.parse( wx.getStorageSync("userinfo")); 
    this.setData({ 
      userInfo: userInfo,
      img: userInfo.avatarUrl,
      imghost: app.globalData.imghost,
      isfirstload:true,
    }) 
    that.getRedActivity();
    that.getShoucangIds();     
  },
  onShow: function () { 
    var that = this
    var ret=foodcart.getFoodlist();
    that.setcart(ret);
    if (this.data.isfirstload){      
      this.setData({
        voiceblock: false,
      })
    }
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height: (res.windowHeight * .69) + 'px'
        })
      }
    }); 
  },
  setcart:function(ret){
    if(ret){
      this.setData({
        foodarr: ret.foodlist,
        totalMoney: ret.buycart.buyamount,
        buycar_num: ret.buycart.buynum,
        cartlist: foodcart.getCartList(),
      })
    }
    
  } ,
  
  getShopInfo: function (e) {
    var that=this;
    let url = util.url.getshop  + '?id='+that.data.shopid
    util.fetchGet(url, function (ret) {
      wx.setNavigationBarTitle({
        title:ret.data.name
      })  
      let shopinfo = {};
      shopinfo.sertime = ret.data.servicetime;
      shopinfo.address = ret.data.address;
      shopinfo.name = ret.data.name;
      shopinfo.id=ret.data.id;
      shopinfo.phone=ret.data.phone;
      shopinfo.pic = ret.data.pic;
      that.setData({
        shopinfo: shopinfo,
      }) 
      console.log(ret);
      wx.setStorageSync("shopinfo", shopinfo);
    }); 
  },
  
  foodlist:function(callback){
    var that = this;
    var foodurl = util.url.food_list + '?shop=' + this.data.shopid
    util.fetchGet(foodurl, function (ret) {
      var types = ret.data.types;
      var foods = ret.data.foods;
      if (!foods) return;
      types.sort(function(a,b){
        return b.snum-a.snum;
      })
      var arr={}; 
      for (var i=0;i<types.length;i++){
        arr['id'+types[i].id]=[];
      }
      for (var i = 0; i < foods.length; i++) {
        foods[i].num = 0;
        foods[i].show = true;
        arr['id' + foods[i].foodType.id].push(foods[i]);
      }
      var foodlist=[];
      for (var i = 0; i < types.length; i++) {
        var typefood = arr['id' + types[i].id];
        if (typefood.length ==0){
          types[i].show=false;
        }else{
          types[i].foodid = typefood[0].id;
          types[i].show = true;
        }
        foodlist = foodlist.concat(arr['id' + types[i].id]);
      }  
      that.setData({
        foodarr: foodlist,
        menu: types 
      })  
      wx.setStorageSync("menus", types);
      var ret=foodcart.oldFoodToNew(foodlist);
      that.foodnick(); //解析菜单别名
      that.setcart(ret);
      if (callback) { 
         
        callback();
      }
    })
  },


  setMenu: function (foodtype,foodid){
    var menu=this.data.menu;
    var isIn=false;
    for(var i=0;i<menu.length;i++){
      if (menu[i].id==foodtype.id){
        isIn=true;
      }
    }
    if (!isIn){
      foodtype.foodid = foodid;
      menu.push(foodtype);
    }
    this.setData({
      menu: menu,
    })
  },
  turnMenu: function (e) {
    var type = e.target.dataset.index;
    var menu=this.data.menu;
    var foodtype=menu[type];

    console.log(type)
    this.setData({
      orderType: type,
      toView: 'foodview'+foodtype.foodid
    })
    this.$apply; 
  },
    
  tabChange: function (e) {
    
    var type = e.currentTarget.dataset.id;
    this.setData({
      orderOrBusiness: type
    })
  },
  
  toFoodDetail: function (e) {
    var id=e.currentTarget.dataset.id;
    var foodarr=this.data.foodarr;
    var food={};
    for (var i = 0; i < foodarr.length;i++){
      if (id==foodarr[i].id){
        food = foodarr[i]
      }
    }
    wx.navigateTo({
      url: '../detail/detail?food=' + JSON.stringify(food),
    })
  },
  
  reduce2: function (e) {
    var id = e.currentTarget.dataset.id;
    var ret = foodcart.addFoodCart(id, -1);
    this.setcart(ret);
    return;
  }, 
  add2: function (e) {
    var id = e.currentTarget.dataset.id;
    var ret = foodcart.addFoodCart(id, 1);
    this.setcart(ret);
    return;   
  },
  
 

  close: function () {
    this.setData({
      block: false
    })
  },
  resetNum: function (e) {
    var typeindex = e.currentTarget.dataset.id;
    this.setData({
      foodtype: typeindex
    })
  },
  
  bindSearchInput:function(e){
    this.setData({
      searchKey:e.detail.value,
      searchinput: e.detail.value,
    })
    this.searchBtn(); 
  }, 
  searchBtn: function () {
    var keyWork = this.data.searchKey;
    var foodarr = this.data.foodarr;
    for (var i = 0; i <foodarr.length;i++){
      if (foodarr[i].name.indexOf(keyWork)<0){
        foodarr[i].show=false;
      }else{
        foodarr[i].show = true;
      }
    }
    this.setData({
      foodarr: foodarr
    })
  },
  

  voiceBlockClose: function () {
    this.setData({
      voiceblock: false
    })
  },
  
  stopVToT:function(){
    this.openDialog();
    var that=this; 
    voiceorder.stopVoice(function(){
      if (that.data.voicesucc){
        that.setData({
          voiceparsetip: ''
        })
      }      
    })    
  },
  startVtoT: function () {
    
    this.startLuyin();
    return ;
    var that = this;
    that.setData({ voiceparsetip:'正在识别录音...'})
   

  },
  continueVtoT: function () {
    var that = this;
    voiceorder.startVtoT(
      function () {
        that.setData({
          voicetext: that.data.voicetext + "," + that.data.nvoicetext
        })
      }
    );
  },
  goToSubmitOrder:function(){
    var that=this;
    var carts=that.parseText();
    /*if (!carts || carts.length == 0) {
      util.showinfo('你点的菜品菜单上不存在，请重新点餐');
      return;
    }*/
    console.log(carts);
    var foodarr = that.data.foodarr;
    for (var i = 0; i < carts.length; i++) {
      for (var j = 0; j < foodarr.length; j++) {
        if (carts[i].id == foodarr[j].id) {         
          var ret = foodcart.addFoodCart(foodarr[j].id, carts[i].num);
        }
      }
    }
    wx.setStorageSync("voiceremark", that.data.voicetext);
    that.settlement();
      
  },

  settlement:function(){
    if (this.data.buycar_num==0){
      util.showinfo("购物车为空,请先添加");
      return;
    }
    wx.navigateTo({
      url: '../submitOrder/submitOrder',
    }) 
  },

  voiceInput:function(e){
    console.log(e.detail.value);
    this.setData({
      voicetext:e.detail.value
    })
  },
  voiceToCart:function(callback){
    ////一份凉面，三份鱿鱼炒饭，两份鸡蛋炒饼，凉皮不要辣椒和香菜，两个卤蛋,下午5点去取
    var that=this;
    var url = 'search/texttocart?text=' + encodeURIComponent(that.data.voicetext) 
    url += "&shopid=" + that.data.shopid;
    util.fetchGet(
      url,
      function(data){
        var carts=data.data.carts;
        var fetchTime = data.data.fetchTime;
        var remark = data.data.remark;
        var foodarr=that.data.foodarr;
        if (!carts || carts.length==0){
          util.showinfo('你点的菜品菜单上不存在，请重新点餐');         
          return; 
        }    

        for (var i = 0; i < carts.length;i++){
          for (var j = 0; j < foodarr.length; j++) {
            if (carts[i].id == foodarr[j].id){              
              var ret = foodcart.addFoodCart(foodarr[j].id, carts[i].num);
            }
          }
        }
        if (callback){
          callback();
        }
      }
    )
  },
  //打开红包
  getPag: function () {   
    wx.navigateTo({
      url: '../myPackage/myPackage?currentTab=1&&shopid='+this.data.shopid,
    })

  },
  //关闭红包
  hasGet: function () {
    this.setData({
      open: false
    })
  },
  showVoiceInfo:function(){
    wx.navigateTo({
      url: '/pages/voicerule/voicerule',
    })
  },
  foodnick:function(){
    var foodarr=this.data.foodarr;
    var foodnickarr=[];
    for (var i = 0; i < foodarr.length;i++){
      var food=foodarr[i];
      if (food.nickname==null || food.nickname==""){
        foodnickarr.push({ id: food.id, nickname: food.name,name:food.name });
        //food.nickname=food.name;  
        //foodnickarr.push(food); 
      }else{
        
        var nicks = food.nickname.split(" ");
        //food.nickname = food.name; 
        foodnickarr.push({ id: food.id, nickname: food.name, name: food.name});
        for (var j = 0; j < nicks.length;j++){
          
          foodnickarr.push({ id: food.id, nickname: nicks[j], name: food.name });
        }

      }
    }
    foodnickarr.sort(function(a,b){
      return b.nickname.length-a.nickname.length;
    })
    this.setData({ foodnickarr: foodnickarr})
    console.log(foodnickarr);
  },
  getTextNum:function(str){
    var foodnickarr = this.data.foodnickarr;
    

    for (var i = 0; i < foodnickarr.length;i++){
      if (str.indexOf(foodnickarr[i].nickname)>=0){
        var food = foodnickarr[i];
        var num=voiceorder.textToNum(str);
        if (num>0){
          
        }else{
          num=1;
        }
        var cart = { id: food.id ,num:num}; 
        return cart;
      }
    }
    return null;    
  },
  parseText:function(){
    var voicetext=this.data.voicetext;
    voicetext=voicetext.replace(",","，");
    var arr=voicetext.split("，")
    var carts=[];
    var cartname={};
    for (var i = 0; i < arr.length;i++){
      var cart=this.getTextNum(arr[i]);      
        if (cart != null) {
          if (!cartname[cart.name]) {
            cartname[cart.name] = cart.name;
            carts.push(cart);
          }          
        }      
    }
    return carts;
  },
  gotocart:function(){
    wx.switchTab({
      url: '/pages/shopcart/cart',
    })
  },
  openDialog: function () {
    wx.hideTabBar({})
    this.setData({
      istrue: true
    })
  },
  closeDialog: function () {
    wx.showTabBar({})
    this.setData({
      istrue: false
    })
  } , 
  startLuyin:function(){
    var that=this;
    voiceorder.startVoice(function (succ, text, file) {
      
      if (succ){
        that.setData({ voicetext: text })
        var voicecarts=that.parseText();
        for (var i = 0; i < voicecarts.length;i++){
          var ret = foodcart.addFoodCart(voicecarts[i].id, voicecarts[i].num);
          that.setcart(ret);
        }
      }else{
        util.showinfo("语音解析失败，请重试");
        console.log(text);
        //that.setData({ voicetext: '语音解析失败，请重试' })
      }
    })
  },
  endLuyin:function(){ 
    voiceorder.stopVoice(function(){
      console.log("stopVoice");
    })
  },
  onShareAppMessage:function(object){
    var form = object.form;
    return {
      title: '美味降临555',
      path: '/pages/index/index?id=6'
    }
  },
  getRedActivity:function(){
    var shopid = this.data.shopid;
    var url = "redpacket/getonlineact?shop=" + shopid;
    var that = this;
    // var url = "/red/listredact";
    util.fetchGet(
      url,
      function (ret) {
        var list = ret.data;
        
        that.setData({
          redact:list,
          redpacket:list.length==0?false:true
        })
      }
    )
  },
  bindShoucang:function(){
    var that=this;
    var url=util.url.collect_add;
    var id=this.data.shopid;
    url+="?id="+id;
    util.fetchGet(
      url,
      function(ret){
        var cslist = that.data.cslist;
        cslist.unshift(id);
        that.setData({
          cslist: cslist,
          is_collect:true
        })
      }
    )
  },
  getShoucangIds:function(){
    var that = this;
    var url = util.url.collect_list_id;
    util.fetchGet(
      url,
      function (ret) {
        var data=ret.data;
        if (data.length>0){
          var is_collect=false;
          for (var i in data){
            if (data[i]==that.data.shopid){
              is_collect=true;
            }
          }
          that.setData({
            cslist: ret.data,
            is_collect: is_collect
          })
        }        
      }
    )
  }

})
